package io.renren.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import io.netty.util.internal.StringUtil;
import io.renren.annotation.Login;
import io.renren.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.CampaignEntity;
import io.renren.entity.PeakEntity;
import io.renren.service.CampaignService;
import io.renren.service.PeakService;
import io.renren.service.UserPeakService;
import io.renren.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-01-20 12:55:41
 */
@RestController
@RequestMapping("api/campaign")
public class CampaignController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private CampaignService campaignService;

    @Autowired
    private PeakService peakService;


    @Autowired
    private UserPeakService userPeakService;

    @Autowired
    private UserService userService;


    /**
     * 列表
     */
    @SysLog("查询项目内容")
    @RequestMapping("/queryContent")
    public R queryByContentOrTagline(String content, int pageId, int pageSize) {
        String queryContent = content;
        List<CampaignEntity> queryList = null;
        try {
            Preconditions.checkArgument(StringUtils.isNotEmpty(content));
            Preconditions.checkArgument(pageId > 0);
            Preconditions.checkArgument(pageSize > 0 && pageSize < 100);
            PageHelper.startPage(pageId, pageSize, true);
            queryList = campaignService.queryByContentOrTagline(queryContent);

        } catch (Exception e) {
            logger.error("error query content {}", e);
        }


        return R.ok().put("result", queryList);
    }

    /**
     * 列表
     */
    @SysLog("按照用户查询项目列表")
    @RequestMapping("/listByUID")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = campaignService.queryPageByUID(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listByUIDTest")
    public R list(@RequestParam("ownerId") String userId) {

        return R.ok().put("page", userId);
    }


    /**
     * 信息
     */
    @SysLog("查询项目列表")
    @RequestMapping("/list")
    public R listALl(@RequestParam Map<String, Object> params) {

        Object queryContent = params.get("content");
        boolean flag = false;
        try {

            if (null == queryContent) {
                flag = true;
            }

            if (null != queryContent && StringUtil.isNullOrEmpty(queryContent.toString())) {
                flag = true;
            }

            if (flag) {

                PageUtils page = campaignService.queryPage(params);
                for (Object item : page.getList()) {
                    double totalPrice = userPeakService.getTotalPriceByCID(((CampaignEntity) item).getId());
                    ((CampaignEntity) item).setTotalPrice(totalPrice);
                }
                return R.ok().put("page", page);
            } else {
                List<CampaignEntity> queryList = null;
                int pageId = Integer.parseInt(params.get("page").toString());
                int pageSize = Integer.parseInt(params.get("limit").toString());

                PageHelper.startPage(pageId, pageSize);
                queryList = campaignService.queryByContentOrTagline(queryContent.toString());
                PageInfo page = new PageInfo(queryList);

                for (CampaignEntity item : queryList) {
                    double totalPrice = userPeakService.getTotalPriceByCID(item.getId());
                    item.setTotalPrice(totalPrice);
                }

                Map<String, Object> queryResult = new HashMap<>();
                queryResult.put("totalCount", page.getTotal());
                queryResult.put("totalPage", page.getPages());
                queryResult.put("list", queryList);
                return R.ok().put("page", queryResult);

            }
        } catch (Exception e) {
            logger.error("error query content {}", e);
        }
        return R.error();

    }


    /**
     * 信息
     */
    @Login
    @SysLog("查询项目内容")
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id, @RequestAttribute("userId") String userId) {
        CampaignEntity campaign = campaignService.selectById(id);
        double totalPrice = userPeakService.getTotalPriceByCID(id);
        campaign.setOwnerImage(userService.getUserPortait(campaign.getOwnerId()));
        campaign.setTotalPrice(totalPrice);
        campaign.setBacker(userPeakService.checkBackerByUid(id, userId));


        return R.ok().put("campaign", campaign);
    }

    /**
     * 保存
     */
    @SysLog("保存项目")
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/save")
    public R save(@RequestBody CampaignRequest campaignRequest) {
        campaignService.insert(campaignRequest.campaignInfo);
        for (PeakEntity item : campaignRequest.peaksList) {
            item.setCampaignId(campaignRequest.campaignInfo.getId());
        }
        peakService.insertBatch(campaignRequest.peaksList);


        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改项目")
    @RequestMapping("/update")
    public R update(@RequestBody CampaignEntity campaign) {
        ValidatorUtils.validateEntity(campaign);
        campaignService.updateAllColumnById(campaign);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除项目")
    @RequestMapping("/deleteByList")
    public R deleteByList(@RequestBody Integer[] ids) {
        campaignService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除项目")
    @RequestMapping("/deleteById/{id}")
    public R deleteById(@PathVariable Integer id) {
        campaignService.deleteById(id);

        return R.ok();
    }

    static class CampaignRequest {

        public CampaignEntity campaignInfo;
        public List<PeakEntity> peaksList;


    }

}
